package com.abc.xxx.controller;

import com.abc.xxx.model.SysConfig;
import com.abc.xxx.util.Result;
import com.alibaba.fastjson.JSON;
import com.abc.xxx.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

@Slf4j
@RestController
@RequestMapping("/sys-config")
public class SysConfigController {

    @Autowired
    private SysConfigService sysConfigService;

    @GetMapping
    public Result findSysConfigs(@RequestParam(value = "key", required = false) String key) {
        String oper = "查询系统配置列表";
        log.info("▶{}, key: {}", oper, key);

        List<SysConfig> list = sysConfigService.findSysConfigs(key);
        return Result.success(oper).list(list);
    }

    @PostMapping
    public Result addSysConfig(@RequestBody String body) {
        String oper = "新增系统配置";
        log.info("▶{}, body: {}", oper, body);

        SysConfig config = JSON.parseObject(body, SysConfig.class);
        if (isBlank(config.getKey())) {
            return Result.error(oper).msg("配置键不能为空");
        }
        if (sysConfigService.isKeyExists(config.getKey())){
            return Result.error(oper).msg("配置键已存在");
        }
        if (isBlank(config.getVal())) {
            return Result.error(oper).msg("配置值不能为空");
        }
        config.setUpdated(LocalDateTime.now());
        sysConfigService.save(config);
        return Result.success(oper).data("id",config.getId()).data("updated", config.getUpdated());
    }

    @DeleteMapping("/{id}")
    public Result deleteSysConfig(@PathVariable("id") Integer id) {
        String oper = "删除系统配置";
        log.info("▶{}, id: {}", oper, id);

        if (id == null) {
            return Result.error(oper).msg("配置id不能为空");
        }
        sysConfigService.removeById(id);
        return Result.success(oper);
    }

    @PatchMapping("/{id}")
    public Result updateSysConfig(@PathVariable("id") Integer id,
                                  @RequestBody String body) {
        String oper = "更新系统配置";
        log.info("▶{}, body: {}", oper, body);
        SysConfig config = JSON.parseObject(body, SysConfig.class);

        if (config.getId() == null) {
            return Result.error(oper).msg("配置id不能为空");
        }
        if (isNotBlank(config.getKey())){
            if (sysConfigService.isUpdateTargetKeyExists(config.getId(),config.getKey())){
                return Result.error(oper).msg("配置键已存在");
            }
        }
        config.setUpdated(LocalDateTime.now());
        sysConfigService.updateById(config);
        return Result.success(oper).data("updated", config.getUpdated());
    }


}
